package voip.ringer.server;



import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import voip.capture.client.VoiceCaptureClient;
import voip.capture.server.VoiceCaptureServer;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class RingerServer extends Service {

	Socket serverSocket;
	public IBinder onBind(Intent intent) {
		return null;
	}

	
	@Override
	public void onDestroy() {
		//code to execute when the service is shutting down
	}
	@Override
	public int onStartCommand(Intent intent, int flags,int startId) {
		super.onStartCommand(intent, flags, startId);
		//code to execute when the service is starting up

		Thread t = new Thread(new Worker(this));
		t.start();
		
		return START_STICKY;
	}
	
	private class Worker implements Runnable{
		RingerServer RS;
		
		public Worker(RingerServer RS){
			this.RS = RS;
		}
		@Override
		public void run() {
			ServerSocket listener = null;
			try {
			      Log.d("RINGER", "Started the server, waiting for client...");
			      listener = new ServerSocket(4445);
			      serverSocket = listener.accept();
			      Log.d("RINGER", "Client Connection Accepted!!! Starting Voice Server");
			      String cl_ip = serverSocket.getRemoteSocketAddress().toString();
			      Log.d("RINGER", "FULL IS " + serverSocket.getRemoteSocketAddress().toString());
			      cl_ip = cl_ip.substring(0,cl_ip.indexOf("/"));
			      
			      Log.d("RINGER", "Client address is " +  cl_ip);

			      
			    //Start Voice Capture Server
			      
			      
			      Intent VoiceCaptServer = new Intent(RingerServer.this, VoiceCaptureServer.class);
			      VoiceCaptServer.putExtra("User_IP",cl_ip);
			      startService(VoiceCaptServer);
			      
				//Start the client activity
				Intent VoiceClientActvity = new Intent(RingerServer.this, VoiceCaptureClient.class);
				VoiceClientActvity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				
				VoiceClientActvity.putExtra("User_IP", cl_ip); //Put address of client in the Voice Client Activity
				RingerServer.this.startActivity(VoiceClientActvity);

				


				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}
}

